from flask import Flask, request, jsonify, render_template
from utils.downloader import init_selenium_driver, download_from_webpage, redis_client, generate_task_id
import threading
import logging
import os
from datetime import datetime

# 设置项目根目录和下载目录的路径
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
DOWNLOADS_DIR = os.path.join(PROJECT_ROOT, 'downloads')
LOGS_DIR = os.path.join(PROJECT_ROOT, 'logs')

# 确保必要的目录存在
os.makedirs(DOWNLOADS_DIR, exist_ok=True)
os.makedirs(LOGS_DIR, exist_ok=True)  # 确保日志目录存在

# 配置日志
def setup_logger():
    """配置日志记录器"""
    log_filename = os.path.join(
        LOGS_DIR, f'app_{datetime.now().strftime("%Y%m%d")}.log')
    os.makedirs(os.path.dirname(log_filename), exist_ok=True)

    formatter = logging.Formatter(
        '%(asctime)s [%(levelname)s] %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    file_handler = logging.FileHandler(log_filename, encoding='utf-8')
    file_handler.setFormatter(formatter)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)

    logger = logging.getLogger('app')
    logger.setLevel(logging.INFO)
    logger.handlers.clear()
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger

# 创建全局 logger 对象
logger = setup_logger()

app = Flask(__name__, static_folder='static')

# 初始化 Selenium 驱动
init_selenium_driver()

@app.route('/')
def index():
    """渲染主页"""
    # 获取最近 10 个下载记录
    download_records = redis_client.lrange('download_records', 0, 9)
    download_records = [eval(record)
                        for record in download_records]  # 将字符串转换为字典
    return render_template('index.html', download_records=download_records)

@app.route('/download', methods=['POST'])
def download():
    """处理下载请求"""
    data = request.get_json()
    url = data.get('url')
    if not url:
        return jsonify({'error': 'URL 是必需的'}), 400

    task_id = generate_task_id(url)
    redis_client.hset(task_id, 'progress', 0)
    redis_client.hset(task_id, 'status', 'in_progress')
    logger.info(f'开始下载任务 {task_id}，网址: {url}')

    # 启动下载线程
    threading.Thread(target=download_from_webpage, args=(url, task_id)).start()

    return jsonify({'message': '下载已开始', 'task_id': task_id}), 200

@app.route('/progress/<task_id>', methods=['GET'])
def progress(task_id):
    """获取下载进度"""
    progress = redis_client.hget(task_id, 'progress')
    status = redis_client.hget(task_id, 'status')
    if progress is None:
        logger.warning(f'未找到任务 {task_id}')
        return jsonify({'error': '未找到任务'}), 404
    logger.info(f'任务 {task_id} 的进度: {int(progress)}%')
    return jsonify({'progress': int(progress), 'status': status.decode('utf-8') if status else 'unknown'})

@app.route('/download-records', methods=['GET'])
def download_records():
    """获取最近的下载记录"""
    download_records = redis_client.lrange('download_records', 0, 9)
    download_records = [eval(record) for record in download_records]  # 将字符串转换为字典
    return jsonify(download_records)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
